<?php
/**
 * @Author: phpzhi<phpzhi@qq.com><https://www.phpzhi.com>
 * @Date: 2019/11/7 10:01
 */

namespace zhi;


use EasyWeChat\Factory;
use EasyWeChat\Kernel\Http\StreamResponse;

class MiniProgram
{
    private static $instance = null;

    public static function options()
    {
        $config = [
            // TODO 后台添加配置
            'app_id' => 'wx90a6efd6ec9dff12',
            'secret' => '8a4ee3fe14b4ababce2ae272401425e6',

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => LOG_PATH . '/mp-wechat.log',
            ],
        ];
        return $config;
    }

    /**
     * 获取小程序实例
     * @param bool $cache
     * @return \EasyWeChat\MiniProgram\Application|null
     */
    public static function application($cache = false)
    {
        (self::$instance === null || $cache === true) && (self::$instance = Factory::miniProgram(self::options()));
        return self::$instance;
    }

    /**
     * 获得用户信息 参数code，获取session_key
     * @param $code
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function getUserInfo($code)
    {
        return self::application()->auth->session($code);
    }

    /**
     * 对加密数据进行解密
     * @param $session
     * @param $iv
     * @param $encryptData
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     */
    public static function encryptor($session, $iv, $encryptData)
    {
        return self::application()->encryptor->decryptData($session, $iv, $encryptData);
    }

    /**
     * 生成小程序码 可接受页面参数较短，生成个数不受限
     * @param $scene
     * @param $page
     * @param $optional
     * @return null string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public static function qrcodeUnlimit($scene, $page, $optional)
    {
        $response = self::application()->app_code->getUnlimit($scene, [
            'page' => $page,
            'width' => $optional['width'] ?: 450,
            'line_color' => $optional['color']
        ]);
        if ($response instanceof StreamResponse) {
            return $response->saveAs($optional['directory'], $optional['filename']);
        }
    }
}